<?php

// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 用户ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   create by allen.qiang
 */
quanli_require('module/base/system/sysUser.class.php');
quanli_require('module/base/company/companyMaster.class.php');
quanli_require('module/base/company/cardApply.class.php');
quanli_require('module/base/system/sysDepartment.class.php');

class ajax_userList {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && is_numeric($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch ($_REQUEST['operFlg']) {

                case 1:
                    $this->searchUserList();
                    break;

                case 2:
                    $this->edit();
                    break;

                case 6:
                    $this->userPersonnel();
                    break;
                case 100:

                    if (!isset($_REQUEST['act']) || !in_array($_REQUEST['act'], array('del', 'edit', 'change'))) {
                        returnJsonData('参数错误');
                    }
                    if ($_REQUEST['act'] == 'edit') {

                        $this->editUser();//新增、修改用户

                    } else if ($_REQUEST['act'] == 'del') {

                        $this->deleteUser();//删除用户

                    } else if ($_REQUEST['act'] == 'change') {

                        $this->changeUse();//启用、禁用用户

                    }

                    break;
            }
        } else {

            $this->toReturn('参数错误');
        }
    }

    /**
     * 返回信息
     * @param string $message
     * @param int $code
     * @param mixed $data
     */
    private function toReturn($message, $code = 400, $data = '') {

        die(json_encode(array('code' => $code, 'message' => $message, 'data' => $data)));
    }

    /**
     * 个人设置
     */
    private function userPersonnel() {

        global $G_PGLOB;

        if (!isset($_REQUEST['trueName'], $_REQUEST['email'], $_REQUEST['mobile'], $_REQUEST['userID'], $_REQUEST['userPwd'], $_REQUEST['repeatPwd']) || empty($_REQUEST['userID'])) {
            $this->toReturn('参数错误');
        }

        if (empty($_REQUEST['trueName'])) {
            $this->toReturn('用户姓名不能为空');
        }

        if (!empty($_REQUEST['userPwd'])) {
            //mod by allen.qiang 20140924 密码规则变为数字，字母，符号 start
            //if (!is_pwd($_REQUEST['userPwd'])) {
            if (!is_pwd_A($_REQUEST['userPwd'])) {
            //mod by allen.qiang 20140924 密码规则变为数字，字母，符号 end
                $this->toReturn('输入的密码格式错误');
            }
            if ($_REQUEST['userPwd'] != $_REQUEST['repeatPwd']) {
                $this->toReturn('两次输入的密码不一致');
            }
        }

        if ( !empty($_REQUEST['mobile']) && !is_mobile($_REQUEST['mobile'])) {
            $this->toReturn('手机号码格式错误');
        }

        if ( !empty($_REQUEST['email']) && !is_email($_REQUEST['email'])) {
            $this->toReturn('电子邮件格式错误');
        }

        try {

            $user_obj = new entity('user_master');
            $user_obj->userID = $_REQUEST['userID'];
            if (!$G_PGLOB->DBCA->fetch($user_obj)) {
                throw new Exception('用户信息没有找到', 404);
            }
            $user_obj->trueName = $_REQUEST['trueName'];
            if (!empty($_REQUEST['userPwd'])) {
                $user_obj->userPwd = md5($_REQUEST['userPwd']);
            }
            $user_obj->mobile = $_REQUEST['mobile'];
            $user_obj->email = $_REQUEST['email'];
            $G_PGLOB->DBCA->save($user_obj);

            $this->toReturn('个人信息修改成功', 200);
        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                $this->toReturn($e->getMessage(), $e->getCode());
            } else {
                error_log($e->getMessage());
                $this->toReturn('系统错误', 500);
            }
        }
    }

    /**
     * 查询用户信息
     */
    private function searchUserList() {

        global $G_PGLOB;

        //实例用户类
        $sysUser = new sysUser($G_PGLOB->DBCA);
        if( isset($_REQUEST['search_departmentID']) ){
            $_REQUEST['departmentID'] =  $_REQUEST['search_departmentID'];
        }

        //查询用户信息
        $user_array = $sysUser->searchUserInfo($_REQUEST);

        //组织返回的数据
        $result_array = array(
            'page' => $_REQUEST['page'],
            'total' => $_REQUEST['count'],
            'rows' => array()
        );

        if ( $user_array ) {

            $edit_permission = $G_PGLOB->has_permission(8);

            foreach ($user_array as &$user) {

                if ( $user['useFlg'] ) {
                    $use_name = '启用';
                    $useFlg = 0;
                } else {
                    $use_name = '禁用';
                    $useFlg = 1;
                }

                if ($user['isSalesman']) {
                    $isSalesman = '是';
                } else {
                    $isSalesman = '否';
                }

                if ($edit_permission) {

                    $operate = '<a href="javascript: void(0);" onclick="user.edit(\'' . $user['userID'] . '\');">修改</a>&nbsp;&nbsp;';
                    $operate .= '<a href="javascript: void(0);" onclick="user.role(\'' . $user['userID'] . '\');">角色</a>';
                    $result_array['rows'][] = array(
                        'id' => $user['userID'],
                        'cell' => array(
                            $operate,
                            $user['userID'],
                            $user['trueName'],
                            $user['mobile'],
                            $user['email'],
                            $user['departmentName']?$user['departmentName']:'',
                         $isSalesman,
                         $user['cityName']?$user['cityName']:'',
                         $user['distributionName']?$user['distributionName']:'',
                            '<a href="javascript: void(0);" onclick="user.change.confirm(\'' . $user['userID'] . '\', ' . $useFlg . ')">' . $use_name . '</a>'
                        )
                    );
                } else {

                    $result_array['rows'][] = array(
                        'id' => $user['userID'],
                        'cell' => array(
                            $user['userID'],
                            $user['trueName'],
                            $user['mobile'],
                            $user['email'],
                            $user['departmentName']?$user['departmentName']:'',
                            $isSalesman,
                            $user['cityName']?$user['cityName']:'',
                            $user['distributionName']?$user['distributionName']:'',
                            $use_name
                        )
                    );
                }
            }
        }

        echo json_encode($result_array);
    }

    /**
     * 新增或修改用户信息
     */
    private function edit() {

        global $G_PGLOB;

        //加载角色类
        quanli_require('module/base/system/sysRole.class.php');

        //实例用户类
        $sysUser = new sysUser($G_PGLOB->DBCA);

        $result_data = array();
        /**
         * =============================
         * 查询用户信息
         * =============================
         */
        if (isset($_REQUEST['userID']) && !empty($_REQUEST['userID'])) {

            //查询用户信息
            $arg_array = array(
                'userID' => $_REQUEST['userID']
            );
            $user_array = $sysUser->searchUserInfo($arg_array);
            if (!$user_array) {
                $this->toError('用户信息没有找到');
            }
            $data_array = $user_array[0];


            $city_array = explode(",",$data_array['cityID']);
            $data_array['city'] = explode(",",$data_array['cityID']);
            $data_array['distribution'] = explode(",", $data_array['distributionID']);


            //查询用户已有的角色信息
            $user_role_array = $sysUser->searchUserRole($_REQUEST['userID']);
            foreach ($user_role_array as $item) {
                $data_array['user_role'][] = $item;
            }

            returnJsonData('ok', 200, $data_array);

        } else {
            returnJsonData('ok', 404);
        }

    }

    /**
     * 保存用户信息
     */
    private function editUser() {

        global $G_PGLOB;
        //实例用户类
        $sysUser = new sysUser($G_PGLOB->DBCA);

        //实例化部门类
        $sysDepartment = new sysDepartment();

        //把得到的城市，配送站数组从新组装成类似（1,2,3）的字符串
        $city_str = "";
        $distribution_str = "";
        $cityName_str = "";
        $distributionName_str = "";
        if( isset($_REQUEST['departmentID'] )){
            //根据部门id查询部门
            $department_obj = new entity('user_department');
            $department_obj->departmentID = $_REQUEST['departmentID'];
            if( $G_PGLOB->DBCA->fetch( $department_obj )){
                $_REQUEST['departmentName'] = $department_obj->departmentName;
            }
            //当部门id存在的时候并且该用户部门没有跨城市，修改该用户大客户下面对应的信息 add by loreta.cheng 2015-06-15 start
            //查询该用户之前所在的部门userID
            $arg_array = array(
                'userID' => $_REQUEST['userID']
            );
            $user_array = $sysUser->searchUserInfo($arg_array);
            //首先查询该用户是否是营销部门的
            $department_array = array();

            //递归查询部门数据
            $sysDepartment->searchDepartment($department_array,104);

            //首先查询该用户是否是营销部门的
            if($sysDepartment->deep_in_array($user_array[0]['departmentID'],$department_array) && $user_array[0]['departmentID']!=$_REQUEST['departmentID']){
       
            //查询新老部门id是否在同一个大队下面
            $departmentResult=$sysDepartment->searchPdepartmentID($user_array[0]['departmentID'],$_REQUEST['departmentID'],$department_array);
            if($departmentResult){
                //实例化大客户类
                $companyMaster = new companyMaster();
                //实例化申领单类
                $cardApply = new cardApply();
                $sysDepar_array = array(
                    'departmentID' =>$_REQUEST['departmentID'],
                    'departmentIDold' =>$user_array[0]['departmentID'],
                    'departmentName' =>$_REQUEST['departmentName'],
                    'userID' =>$_REQUEST['userID']
                    );
                $companyMaster->changeCompanyDepartment($sysDepar_array);
                $cardApply->changeCardDepartment($sysDepar_array);
                }
            }

        //当部门id存在的时候并且该用户部门没有跨城市，修改该用户大客户下面对应的信息 add by loreta.cheng 2015-06-15 end
        }

        $cityName = '';
        if( $_REQUEST['cityID'] ){
            foreach( $_REQUEST['cityID'] as $res){
                //根据城市id查询城市
                $region_obj = new entity('sys_region');
                $region_obj->id = $res;
                if( $G_PGLOB->DBCA->fetch( $region_obj )){
                    $cityName .= $region_obj->name .',' ;
                }
            }
            $_REQUEST['cityName'] = substr( $cityName,0,strrpos( $cityName,',') );
        }

        $distributionName = '';
        if( $_REQUEST['distributionID'] ){
            foreach( $_REQUEST['distributionID'] as $val){
                //根据配送站id查询配送站
                $distribution_obj = new entity('sys_distribution');
                $distribution_obj->distribution_id = $val;
                if( $G_PGLOB->DBCA->fetch( $distribution_obj )){
                    $distributionName .= $distribution_obj->distribution_name .',' ;
                }
            }
            $_REQUEST['distributionName'] = substr( $distributionName,0,strrpos( $distributionName,',') );
        }



        $city_str = isset($_REQUEST['cityID']) ? implode(",",$_REQUEST['cityID']) : "";
        $distribution_str = isset($_REQUEST['distributionID']) ? implode(",",$_REQUEST['distributionID']) : "";
        $_REQUEST['cityID'] = $city_str;
        $_REQUEST['distributionID'] = $distribution_str;

        

        //新增或修改用户信息
        $_REQUEST['operator'] = $G_PGLOB->currentUserID;
        $_REQUEST['departmentID'] = $_REQUEST['departmentID'];
        $result_array = $sysUser->editUser($_REQUEST);

        echo json_encode($result_array);
    }

    /**
     * 启用或禁用用户
     */
    private function changeUse() {

        global $G_PGLOB;

        //实例化用户类
        $sysUser = new sysUser($G_PGLOB->DBCA);

        //启用或禁用用户
        $result_array = $sysUser->changeUserUse($_REQUEST);

        echo json_encode($result_array);
    }
    
    /**
     * 删除用户
     */
    private function deleteUser() {

        if (!isset($_REQUEST['user_arry']) || !is_array($_REQUEST['user_arry'])) {
            $this->toReturn('参数错误');
        }

        global $G_PGLOB;

        //实例化用户类
        $sysUaer = new sysUser($G_PGLOB->DBCA);

        $result_array = $sysUaer->deleteUser($_REQUEST['user_arry']);

        echo json_encode($result_array);
    }

}
